<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">

		<title>购物车页面</title>

		<link href="../AmazeUI-2.4.2/assets/css/amazeui.css" rel="stylesheet" type="text/css" />
		<link href="../basic/css/demo.css" rel="stylesheet" type="text/css" />
		<link href="../css/cartstyle.css" rel="stylesheet" type="text/css" />
		<link href="../css/optstyle.css" rel="stylesheet" type="text/css" />
		<link href="../js/shopcart/css/reset.css" rel="stylesheet" type="text/css" />
		<link href="../js/shopcart/css/carts.css" rel="stylesheet" type="text/css" />
		<script type="text/javascript" src="../js/jquery.js"></script>
		
		<script type="text/javascript" src="../js/common.js"></script>
	</head>

	<body>

		<!--顶部导航条 -->
		<div class="am-container header">
			<ul class="message-l">
				<div class="topMessage">
					<div class="menu-hd" id="indexHeader">
					</div>
				</div>
			</ul>
			<ul class="message-r">
				<div class="topMessage home">
					<div class="menu-hd">
						<a href="index.html" target="_top" class="h">商城首页</a>
					</div>
				</div>
				<div class="topMessage my-shangcheng">
					<div class="menu-hd MyShangcheng">
						<a href="pindex.html" target="_top"><i class="am-icon-user am-icon-fw"></i>个人中心</a>
					</div>
				</div>
				<div class="topMessage mini-cart">
					<div class="menu-hd">
						<a id="mc-menu-hd" href="shopcart.html" target="_top"><i class="am-icon-shopping-cart  am-icon-fw"></i><span>购物车</span><strong id="J_MiniCartNum" class="h"></strong></a>
					</div>
				</div>
				
			</ul>
		</div>


			<!--购物车 -->
			<section class="cartMain">
				<div class="cartMain_hd">
					<ul class="order_lists cartTop">
						<li class="list_chk">
							<!--所有商品全选-->
							<input type="checkbox" id="all" class="whole_check">
							<label for="all"></label> 全选
						</li>
						<li class="list_con">商品名称</li>
						<li class="list_info"></li>
						<li class="list_price">单价</li>
						<li class="list_amount">数量</li>
						<li class="list_sum">金额</li>
						<li class="list_op">操作</li>
					</ul>
				</div>

				<div class="cartBox">
					<div class="order_content">
						
					</div>
				</div>

				<!--底部-->
				<div class="bar-wrapper">
					<div class="bar-right">
						<div class="piece">已选商品<strong class="piece_num">0</strong>件</div>
						<div class="totalMoney">共计: <strong class="total_text">0.00</strong></div>
						<div class="calBtn">
							<a href="javascript:;" onclick="gotoPay()">结算</a>
						</div>
					</div>
				</div>
			</section>
			<section class="model_bg"></section>
			<section class="my_model">
				<p class="title">删除宝贝<span class="closeModel">X</span></p>
				<p>您确认要删除该宝贝吗？</p>
				<div class="opBtn">
					<a href="javascript:;" class="dialog-sure">确定</a>
					<a href="javascript:;" class="dialog-close">关闭</a>
				</div>
			</section>
			
			<script>
				$(function(){
					/*检验用户是否登录*/
					if (getCookie("username") == null || getCookie("userid") == null) {
	                    window.location.href="login.html";
	                    return;
				    }else{
				    	$("#indexHeader").append(`
	                            <a href="#" target="_top" class="h">您好，${getCookie("username")}</a>
	                            <a href="javascript:void(0);" onclick="clearCookie()">退出</a>`
	                    );
				    }
					
					//根据userid查询用户购物车数据
					var userid=getCookie("userid");
					$.ajax({
						type:"get",
						url:"/shopcart/selectByUserid/"+userid,
						async:false,
						success:function(result){
							for(let i=0;i<result.length;i++){
								//购物车主键id
								var item_carid=result[i].id;
								//商品id
								var item_goodsid=result[i].goodsid;
								//商品数量
								var item_goodsnum=result[i].goodsnum;
								//商品详情
								var goods;
								$.ajax({
									type:"get",
									url:"/goods/info/"+item_goodsid,
									async:false,
									success:function(result){
										goods=result.data;
									}
								});
								//单价
								var item_goodsprice=goods.price;
								//总价
								var item_totalprice=item_goodsnum*item_goodsprice;
								
								var html=`<ul class="order_lists">
											<li class="list_chk">
												<input type="hidden" class="son_carid" value="${item_carid}"/>
												<input type="hidden" class="son_goodsid" value="${goods.id}"/>
												<input type="checkbox" id="checkbox_${i}" class="son_check">
												<label for="checkbox_${i}"></label>
											</li>
											<li class="list_con">
												<div class="list_img">
													<a href="javascript:;"><img src="${goods.img1}" alt=""></a>
												</div>
												<div class="list_text">
													<a href="javascript:;">${goods.goodsname}</a>
												</div>
											</li>
											<li class="list_info">
											</li>
											<li class="list_price">
												<p class="price">￥${item_goodsprice}</p>
											</li>
											<li class="list_amount">
												<div class="amount_box">
													<a href="javascript:;" class="reduce reSty">-</a>
													<input type="text" value="${result[i].goodsnum}" class="sum">
													<a href="javascript:;" class="plus">+</a>
												</div>
											</li>
											<li class="list_sum">
												<p class="sum_price">￥${item_totalprice}</p>
											</li>
											<li class="list_op">
												<p class="del">
													<a href="javascript:;" class="delBtn">移除商品</a>
												</p>
											</li>
										</ul>`;
								
								$(".order_content").append(html);
							}
						}
					});
					
					
					//全局的checkbox选中和未选中的样式
				    var $allCheckbox = $('input[type="checkbox"]'),     //全局的全部checkbox
				        $wholeChexbox = $('.whole_check'),
				        $cartBox = $('.cartBox'),                       //每个商铺盒子
				        $shopCheckbox = $('.shopChoice'),               //每个商铺的checkbox
				        $sonCheckBox = $('.son_check');                 //每个商铺下的商品的checkbox
				    $allCheckbox.click(function () {
				        if ($(this).is(':checked')) {
				            $(this).next('label').addClass('mark');
				        } else {
				            $(this).next('label').removeClass('mark')
				        }
				    });

				    //===============================================全局全选与单个商品的关系================================
				    $wholeChexbox.click(function () {
				        var $checkboxs = $cartBox.find('input[type="checkbox"]');
				        if ($(this).is(':checked')) {
				            $checkboxs.prop("checked", true);
				            $checkboxs.next('label').addClass('mark');
				        } else {
				            $checkboxs.prop("checked", false);
				            $checkboxs.next('label').removeClass('mark');
				        }
				        totalMoney();
				    });


				    $sonCheckBox.each(function () {
				        $(this).click(function () {
				            if ($(this).is(':checked')) {
				                //判断：所有单个商品是否勾选
				                var len = $sonCheckBox.length;
				                var num = 0;
				                $sonCheckBox.each(function () {
				                    if ($(this).is(':checked')) {
				                        num++;
				                    }
				                });
				                if (num == len) {
				                    $wholeChexbox.prop("checked", true);
				                    $wholeChexbox.next('label').addClass('mark');
				                }
				            } else {
				                //单个商品取消勾选，全局全选取消勾选
				                $wholeChexbox.prop("checked", false);
				                $wholeChexbox.next('label').removeClass('mark');
				            }
				        })
				    })

    //店铺有一个未选中，全局全选按钮取消对勾，若店铺全选中，则全局全选按钮打对勾。
    $shopCheckbox.each(function () {
        $(this).click(function () {
            if ($(this).is(':checked')) {
                //判断：店铺全选中，则全局全选按钮打对勾。
                var len = $shopCheckbox.length;
                var num = 0;
                $shopCheckbox.each(function () {
                    if ($(this).is(':checked')) {
                        num++;
                    }
                });
                if (num == len) {
                    $wholeChexbox.prop("checked", true);
                    $wholeChexbox.next('label').addClass('mark');
                }

                //店铺下的checkbox选中状态
                $(this).parents('.cartBox').find('.son_check').prop("checked", true);
                $(this).parents('.cartBox').find('.son_check').next('label').addClass('mark');
            } else {
                //否则，全局全选按钮取消对勾
                $wholeChexbox.prop("checked", false);
                $wholeChexbox.next('label').removeClass('mark');

                //店铺下的checkbox选中状态
                $(this).parents('.cartBox').find('.son_check').prop("checked", false);
                $(this).parents('.cartBox').find('.son_check').next('label').removeClass('mark');
            }
            totalMoney();
        });
    });


    //店铺$sonChecks有一个未选中，店铺全选按钮取消选中，若全都选中，则全选打对勾
    $cartBox.each(function () {
        var $this = $(this);
        var $sonChecks = $this.find('.son_check');
        $sonChecks.each(function () {
            $(this).click(function () {
                if ($(this).is(':checked')) {
                    //判断：如果所有的$sonChecks都选中则店铺全选打对勾！
                    var len = $sonChecks.length;
                    var num = 0;
                    $sonChecks.each(function () {
                        if ($(this).is(':checked')) {
                            num++;
                        }
                    });
                    if (num == len) {
                        $(this).parents('.cartBox').find('.shopChoice').prop("checked", true);
                        $(this).parents('.cartBox').find('.shopChoice').next('label').addClass('mark');
                    }

                } else {
                    //否则，店铺全选取消
                    $(this).parents('.cartBox').find('.shopChoice').prop("checked", false);
                    $(this).parents('.cartBox').find('.shopChoice').next('label').removeClass('mark');
                }
                totalMoney();
            });
        });
    });


    //=================================================商品数量==============================================
    var $plus = $('.plus'),
        $reduce = $('.reduce'),
        $all_sum = $('.sum');
    $plus.click(function () {
        var $inputVal = $(this).prev('input'),
            $count = parseInt($inputVal.val())+1,
            $carid=$(this).parents('.order_lists').find(".son_carid").val(),
            $obj = $(this).parents('.amount_box').find('.reduce'),
            $priceTotalObj = $(this).parents('.order_lists').find('.sum_price'),
            $price = $(this).parents('.order_lists').find('.price').html(),  //单价
            $priceTotal = round($count*$price.substring(1),2);
        $inputVal.val($count);
        $priceTotalObj.html('￥'+$priceTotal);
        if($inputVal.val()>1 && $obj.hasClass('reSty')){
            $obj.removeClass('reSty');
        }
        totalMoney();
        
        //更新到数据库
        var data={"id":$carid,"goodsnum":$count};
        console.log(data);
        $.ajax({
        	type:"post",
        	data:JSON.stringify(data),
        	contentType:"application/json;charset=UTF-8",
        	url:"/shopcart/update",
        	async:true
        });
    });

    $reduce.click(function () {
        var $inputVal = $(this).next('input'),
            $count = parseInt($inputVal.val())-1,
            $carid=$(this).parents('.order_lists').find(".son_carid").val(),
            $priceTotalObj = $(this).parents('.order_lists').find('.sum_price'),
            $price = $(this).parents('.order_lists').find('.price').html(),  //单价
            $priceTotal = round($count*$price.substring(1),2);
        if($inputVal.val()>1){
            $inputVal.val($count);
            $priceTotalObj.html('￥'+$priceTotal);
            //更新到数据库
	        var data={"id":$carid,"goodsnum":$count}
	        $.ajax({
	        	type:"post",
	        	data:JSON.stringify(data),
	        	url:"/shopcart/update",
	        	contentType:"application/json;charset=UTF-8",
	        	async:true
	        });
        }
        if($inputVal.val()==1 && !$(this).hasClass('reSty')){
            $(this).addClass('reSty');
            var data={"id":$carid,"goodsnum":$count}
	        $.ajax({
	        	type:"post",
	        	data:JSON.stringify(data),
	        	url:"/shopcart/update",
	        	contentType:"application/json;charset=UTF-8",
	        	async:true
	        });
        }
        totalMoney();
    });

    $all_sum.keyup(function () {
        var $count = 0,
            $priceTotalObj = $(this).parents('.order_lists').find('.sum_price'),
            $price = $(this).parents('.order_lists').find('.price').html(),  //单价
            $priceTotal = 0;
        if($(this).val()==''){
            $(this).val('1');
        }
        $(this).val($(this).val().replace(/\D|^0/g,''));
        $count = $(this).val();
        $priceTotal = round($count*($price.substring(1)),2);
        $(this).attr('value',$count);
        $priceTotalObj.html('￥'+$priceTotal);
        totalMoney();
    })

    //======================================移除商品========================================
    var $order_lists = null;
    var $order_content = '';
    $('.delBtn').click(function () {
        $order_lists = $(this).parents('.order_lists');
        $order_content = $order_lists.parents('.order_content');
        $('.model_bg').fadeIn(300);
        $('.my_model').fadeIn(300);
    });

    //关闭模态框
    $('.closeModel').click(function () {
        closeM();
    });
    $('.dialog-close').click(function () {
        closeM();
    });
    function closeM() {
        $('.model_bg').fadeOut(300);
        $('.my_model').fadeOut(300);
    }
    //确定按钮，移除商品
    $('.dialog-sure').click(function () {
    	var remove_goodsid=$order_lists.find(".son_goodsid").val();
    	var remove_carid=$order_lists.find(".son_carid").val();
    	console.log("移除的商品id:"+remove_goodsid);
    	console.log("移除的购物车id:"+remove_carid);
    	$.ajax({
    		type:"get",
    		url:"/shopcart/delete/"+remove_carid,
    		success:function(){
    			$order_lists.remove();
		        if($order_content.html().trim() == null || $order_content.html().trim().length == 0){
		            $order_content.parents('.cartBox').remove();
		        }
		        closeM();
		        $sonCheckBox = $('.son_check');
		        totalMoney();
    		}
    	});
    })

    //======================================总计==========================================

    function totalMoney() {
        var total_money = 0.00;
        var total_count = 0;
        var calBtn = $('.calBtn a');
        $sonCheckBox.each(function () {
            if ($(this).is(':checked')) {
                var goods =$(this).parents('.order_lists').find('.sum_price').html().substring(1);
                var num =  parseInt($(this).parents('.order_lists').find('.sum').val());
                console.log(goods);
                total_money+=Number(goods);
                total_count += num;
            }
        });
        $('.total_text').html('￥'+round(total_money,2));
        $('.piece_num').html(total_count);

        // console.log(total_money,total_count);

        if(total_money!=0 && total_count!=0){
            if(!calBtn.hasClass('btn_sty')){
                calBtn.addClass('btn_sty');
            }
        }else{
            if(calBtn.hasClass('btn_sty')){
                calBtn.removeClass('btn_sty');
            }
        }
    }
				})
			</script>
			
			<script>
				function round(num,dec){ 
				    var strNum = num + '';/*把要转换的小数转换成字符串*/
				    var index = strNum.indexOf("."); /*获取小数点的位置*/
				    if(index < 0) {
				        return num;/*如果没有小数点，那么无需四舍五入，返回这个整数*/
				    }
				    var n = strNum.length - index -1;/*获取当前浮点数，小数点后的位数*/
				    if(dec < n){ 
				    	/*把小数点向后移动要保留的位数，把需要保留的小数部分变成整数部分，只留下不需要保留的部分为小数*/ 
				        var e = Math.pow(10, dec);
				        num = num * e;
				        /*进行四舍五入，只保留整数部分*/
				        num = Math.round(num);
				        /*再把原来小数部分还原为小数*/
				        return num / e;
				    } else { 
				        return num;/*如果当前小数点后的位数等于或小于要保留的位数，那么无需处理，直接返回*/
				    } 
				}
				
				/**
				 * 跳转付款结算页面
				 */
				function gotoPay(){
					var idsarray=[];
					$('.son_check').each(function () {
			            if ($(this).is(':checked')) {
			                var carid =$(this).parents('.order_lists').find('.son_carid').val();
			                idsarray.push(carid);
			            }
			        });
			        var ids=idsarray.join(",");
			        window.location.href="cartpay.html?cartids="+ids;
				}
			</script>
	</body>

</html>